import { existsSync, readFileSync, readdirSync, writeFileSync, unlinkSync } from "fs";
import { join } from "path";
import { EOL } from "os";

export interface ICfg {
    plat: string;
    projectBasePath: string;
    jsonPath: string;
    outputUrl: string;
    exportName: string;
}

export function merge(cfgUrl: string) {
    if (!existsSync(join(cfgUrl))) {
        console.log('no such file:', cfgUrl);
        return;
    }
    let cfgStr = readFileSync(join(cfgUrl)).toString();
    let cfg: ICfg = JSON.parse(cfgStr);
    if (existsSync(join(cfg.outputUrl))) {
        unlinkSync(join(cfg.outputUrl));
    }
    let jsonDir = join(cfg.projectBasePath, cfg.jsonPath);
    let files = readdirSync(jsonDir);
    let fileListName = files.filter(f => f == '_filelist_.json')[0];
    if (fileListName) {
        let tempList = cfg.outputUrl.split(EOL);
        let targetFn = tempList[tempList.length - 1];
        if (targetFn.indexOf('.js') < 0) {
            console.log('no set output name, eg: "tabledata.js"');
            return;
        }
        let exportName = cfg.exportName ? cfg.exportName : 'tableData';
        let fileContent = '"use strict";\nvar tableData = {\n';
        let fileEnd = `};\nif (window) {\nwindow["${exportName}"] = tableData;\n}`;


        let fileListStr = readFileSync(join(jsonDir, fileListName)).toString();
        // firstContent += getFileContent(fileListName, fileListStr);
        let fileList: string[] = JSON.parse(fileListStr);
        fileList.forEach(fln => {
            if (!existsSync(join(jsonDir, fln))) {
                return;
            }
            let str = readFileSync(join(jsonDir, fln)).toString();
            // if (cfg.plat == 'web') {
            fileContent += getFileContent(fln, str);
            // } else {
            //     if (first.indexOf(fln) >= 0) {
            //         fileContent += getFileContent(fln, str);
            //     } else {
            //         secondContent += getFileContent(fln, str);
            //     }
            // }
        })

        fileContent += fileEnd
        // if (cfg.plat == 'web') {
        writeFileSync(join(cfg.projectBasePath, cfg.outputUrl), fileContent)
        // } else {
        //     let wxpathTemp = tableCfg[type + 'Path'] + '';
        //     let wxpaths = wxpathTemp.split(',');
        //     writeFileSync(join(projectBasePath, wxpaths[0], targetFn), fileContent)
        //     writeFileSync(join(projectBasePath, wxpaths[1], targetFn2), secondContent)
        // }
        console.log(`file "${cfg.outputUrl}" has created `);

    }

    function getFileContent(fn: string, content: string) {
        let fn0 = fn.split('.')[0];
        let txt = `\n${fn0} : ${content},\n`;
        return txt;
    }
}